//
//  SINATecIssueMsgViewController.m
//  sinashebao
//
//  Created by  androidlongs on 2018/1/2.
//  Copyright © 2018年  androidlongs. All rights reserved.
//

#import "SINATecIssueMsgViewController.h"
#import "SINACircularBeadUtils.h"
#import "SINACustomModelPickView.h"
#import "SINATecCourseModel.h"
#import "SINAMainMsgViewController.h"

@interface SINATecIssueMsgViewController ()<UITextFieldDelegate,UITextViewDelegate,CustomModelPickViewDelegate>
//选择接收部门
@property (weak, nonatomic) IBOutlet UIView *selectDepartmentView;
@property (weak, nonatomic) IBOutlet UILabel *selectDepartMentLabel;
@property (strong, nonatomic)NSMutableArray *selectDepartArray;
@property (strong, nonatomic)SINATecCourseModel *selectDepartmentModel;
//选择接收班级
@property (weak, nonatomic) IBOutlet UIView *selectClassView;
@property (weak, nonatomic) IBOutlet UILabel *selectClassLabel;
@property (strong, nonatomic)NSMutableArray *selectClassArray;
@property (strong, nonatomic)SINATecCourseModel *selectClassModel;
//输入标题
@property (weak, nonatomic) IBOutlet UITextField *inputTitleTextField;
//输入内容的内容框
@property (weak, nonatomic) IBOutlet UITextView *inputDesTextView;
@property (weak, nonatomic) IBOutlet UILabel *commitLabel;

@end

@implementation SINATecIssueMsgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"发布通知";
    self.commitLabel.backgroundColor=baseSelectColor;
    self.selectClassArray=[[NSMutableArray alloc]init];
    self.selectDepartArray=[[NSMutableArray alloc]init];
    [SINACircularBeadUtils makeCircularBead:3 andView:self.commitLabel];
    self.inputDesTextView.delegate=self;
    
    
    UIView *rightView =[[UIView alloc]initWithFrame:CGRectMake(0,0,40,50)];
    UIButton *rightButton =[[UIButton alloc]initWithFrame:CGRectMake(10,0,40,35)];
    [rightButton addTarget:self action:@selector(moreDataFunction) forControlEvents:UIControlEventTouchUpInside];
    [rightView addSubview:rightButton];
    [rightButton setImage:[UIImage imageNamed:@"more_msg"] forState:UIControlStateNormal];
    UIBarButtonItem *rightButtonView = [[UIBarButtonItem alloc]initWithCustomView:rightView ];
    self.navigationItem.rightBarButtonItem=rightButtonView;
    
    
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.selectDepartmentView andWithBlick:^(UIView *view) {
        [self showSelectDepartmentFunction];
    }];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.selectClassView andWithBlick:^(UIView *view) {
        [self showSelectClassFunction];
    }];
    [[SINAUiviewClickLiserner alloc]viewClickFunction:self.commitLabel andWithBlick:^(UIView *view) {
        [self commitMsgData];
    }];
}
-(void)moreDataFunction{
    SINAMainMsgViewController
    *msgController = [[SINAMainMsgViewController alloc]initWithNibName:@"SINAMainMsgViewController" bundle:nil];
    msgController.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:msgController animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITextViewDelegate
- (void)textViewDidEndEditing:(UITextView *)textView
{
    if(textView.text.length < 1){
        textView.text = @"请输入您要发布的内容（限200字以内）";
        
    }
}
- (void)textViewDidBeginEditing:(UITextView *)textView
{
    if([textView.text isEqualToString:@"请输入您要发布的内容（限200字以内）"]){
        textView.text=@"";
    }
}


-(void) showSelectDepartmentFunction{
    
    
    if(self.selectDepartArray.count==0){
        //加载部门信息
        [self loadingDepartmentListNetData];
    }else{
        
        SINACustomModelPickView *pickerSingle = [[SINACustomModelPickView alloc]init];
        
        [pickerSingle setDataArray:self.selectDepartArray];
        [pickerSingle setDefalutSelectRowStr:0];
        pickerSingle.titleLabel.text=@"选择部门";
        pickerSingle.tag=100;
        
        [pickerSingle setDelegate:self];
        
        [pickerSingle show];
        [self.view endEditing:YES];
    }
}

-(void) showSelectClassFunction{
    if(self.selectClassArray.count==0){
        //加载班级信息
        [self loadingClassListNetData];
    }else{
        
        
        SINACustomModelPickView *pickerSingle = [[SINACustomModelPickView alloc]init];
        
        [pickerSingle setDataArray:self.selectClassArray];
        [pickerSingle setDefalutSelectRowStr:0];
        pickerSingle.titleLabel.text=@"选择班级";
        pickerSingle.tag=101;
        
        [pickerSingle setDelegate:self];
        
        [pickerSingle show];
        [self.view endEditing:YES];
    }
}

#pragma mark - CustomModelPickViewDelegate Mehod
-(void)customModelPickView:(SINACustomModelPickView *)customPickView selectedTitle:(SINACommonPopModel *)selectedModel{
    
    SINATecCourseModel *model =(SINATecCourseModel *)selectedModel.model;
    if (customPickView.tag==100) {
        //选择部门
        self.selectDepartmentModel = model;
        self.selectDepartMentLabel.text=selectedModel.title;
        
        self.selectClassModel = nil;
        self.selectClassLabel.text=@"请选择";
    }else{
        //选择班级
        self.selectClassModel = model;
        self.selectClassLabel.text=selectedModel.title;
        
        self.selectDepartmentModel=nil;
        self.selectDepartMentLabel.text=@"请选择";
    }
}
-(void)dismissCustomPickView:(SINACustomModelPickView *)customPickView{
    
}

#pragma mark - BasePickViewDelegate method
- (void)dismissBasePickView:(SINABasePickView *)customPickView
{
    
}

//加载部门
-(void)loadingDepartmentListNetData{

    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //用户的uuid String uuid
    
    //科目id String subjectid
    //排序 String orderInfo: 2 从低到高；  1 从高到低； 0 默认
    
    [dict setObject:[NSString stringWithFormat:@"%@", [[SINACommonUserHelper share]getUserModel].userUid] forKey:@"uuid"];
    
    //班级id String classifyid
    //[dict setObject:self.model.classifyid forKey:@"classifyid"];
    
    [self.selectDepartArray removeAllObjects];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@",baseUrl,getDepartmentListUrl] withParamters:dict success:^(id responseData) { 
        [weakSelf stopLoading];
        NSString *code = responseData[@"code"];
        
        if ([code isEqualToString:@"1000"]) {
            NSArray *result = responseData[@"content"];
            if (result==nil||result.count==0) {
                [YPXToastView showToastViewWithText:@"暂无部门信息" andDuration:2 andParentView:self.view];
            } else {
                //有班级信息
                for(NSInteger i=0;i<result.count;i++){
                    NSDictionary *dic = result[i];
                    
                    SINATecCourseModel *model = [[SINATecCourseModel alloc]initWithDict:dic];
                    SINACommonPopModel *popModel = [[SINACommonPopModel alloc]init];
                    popModel.title = model.name;
                    popModel.model=model;
                    [self.selectDepartArray addObject:popModel];
                    
                }
                [self showSelectDepartmentFunction];
            }
            
            
        }else{
            
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
            
            
        }

    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        
    }];
}

//加载班级
-(void)loadingClassListNetData{

    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //用户的uuid String uuid
    
    //科目id String subjectid
    //排序 String orderInfo: 2 从低到高；  1 从高到低； 0 默认
    
    
    
    [dict setObject:[NSString stringWithFormat:@"%@", [[SINACommonUserHelper share]getUserModel].userUid] forKey:@"uuid"];
    
    //班级id String classifyid
    //[dict setObject:self.model.classifyid forKey:@"classifyid"];
    
    [self.selectClassArray removeAllObjects];
    
    WeakSelf;
    [CXAFNHttpRequestUtils httpGetRequest:[NSString stringWithFormat:@"%@%@",baseUrl,getClassifyByTeacherUuidUrl] withParamters:dict success:^(id responseData) {
        [weakSelf stopLoading];
        NSString *code = responseData[@"code"];
        
        if ([code isEqualToString:@"1000"]) {
            NSArray *result = responseData[@"content"];
            if (result==nil||result.count==0) {
                [YPXToastView showToastViewWithText:@"暂无部门信息" andDuration:2 andParentView:self.view];
            } else {
                //有班级信息
                for(NSInteger i=0;i<result.count;i++){
                    NSDictionary *dic = result[i];
                    
                    SINATecCourseModel *model = [[SINATecCourseModel alloc]initWithDict:dic];
                    SINACommonPopModel *popModel = [[SINACommonPopModel alloc]init];
                    popModel.title = model.name;
                    popModel.model=model;
                    [self.selectClassArray addObject:popModel];
                    
                }
                [self showSelectClassFunction];
            }
            
            
        }else{
            
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
            
            
        }
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"加载数据失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        
    }];
}


//提交数据
-(void)commitMsgData{
    
    if (self.selectDepartmentModel==nil&&self.selectClassModel==nil) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请选择部门" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    
    
    NSString *title= self.inputTitleTextField.text;
    if (title==nil|| [title isEqualToString:@""]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请输入标题" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    NSString *msgContent= self.inputDesTextView.text;
    if (msgContent==nil|| [msgContent isEqualToString:@""] ||[msgContent isEqualToString:@"请输入您要发布的内容（限200字以内）"]) {
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"请输入消息内容" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        return;
    }
    
    [self startLoading];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    //用户的uuid String uuid
    [dict setObject:[NSString stringWithFormat:@"%@", [[SINACommonUserHelper share]getUserModel].userUid] forKey:@"createuseruuid"];
    //发布者uuid createuseruuid
    //消息标题（20字符） title
    [dict setObject:[NSString stringWithFormat:@"%@", title] forKey:@"title"];
    //消息内容（200字符）content
    [dict setObject:[NSString stringWithFormat:@"%@", msgContent] forKey:@"content"];
    if(self.selectDepartmentModel!=nil){
        //要发给的部门id,多个部门用逗号分隔（eg 1,2,3）departmentIds
        [dict setObject:[NSString stringWithFormat:@"%@", self.selectDepartmentModel.universityid] forKey:@"departmentIds"];
    }
    if(self.selectClassModel!=nil&&self.selectClassModel.classifyid!=0){
        //要发给的班级id,多个班级用逗号分隔（eg 1,2,3 String classIds
        [dict setObject:[NSString stringWithFormat:@"%ld", self.selectClassModel.classifyid] forKey:@"classIds"];
    }
    
    
    
    
    
    
    NSMutableDictionary *dict2 = [[NSMutableDictionary alloc]init];
    
    [dict2 setObject:[SINAHttpRequestUtils encodeDicParams:dict] forKey:@"sj"];
    
    [self.selectClassArray removeAllObjects];
    
    WeakSelf;
    
    [CXAFNHttpRequestUtils httpPostRequest:[NSString stringWithFormat:@"%@%@",baseUrl,releaseMessageUrl] withParamters:dict2 success:^(id responseData) {
        
        NSString *code = responseData[@"code"];
        
        if ([code isEqualToString:@"1000"]) {
//            NSArray *result = responseData[@"content"];
//            self.loadingView.text=@"发布成功";
            
            [YPXToastView showToastViewWithText:@"发布成功" andDuration:2 andParentView:weakSelf.view];
            //发送成功
            dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, 2 * NSEC_PER_SEC);
            dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
                // do something
                [weakSelf stopLoading];
                [self moreDataFunction];
                //[self.navigationController popViewControllerAnimated:YES];
            });
            
        }else{
            [weakSelf stopLoading];
            NSString *message =responseData[@"message"];
            WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:message sureBtn:@"确定"
                                                                 cancleBtn:nil];
            [alertView showXLAlertView];
    
        }
        
    } failure:^(NSError *error, NSInteger errCode) {
        DLog(@"加载 失败  %@ ",error.debugDescription);
        [weakSelf stopLoading];
        
        WISAlertView *alertView =   [[WISAlertView alloc]initWithTitle:@"提示" message:@"发送数据失败" sureBtn:@"确定"
                                                             cancleBtn:nil];
        [alertView showXLAlertView];
        
    }];
}

@end
